package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.domain.IotMsgService;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 设别数据信息表Service业务层处理
 * 
 * @author dcl
 * @date 2025-05-25
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 查询设别数据信息表
     * 
     * @param id 设别数据信息表主键
     * @return 设别数据信息表
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设别数据信息表列表
     * 
     * @param deviceData 设别数据信息表
     * @return 设别数据信息表
     */


    /**
     * 新增设别数据信息表
     * 
     * @param deviceData 设别数据信息表
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设别数据信息表
     * 
     * @param deviceData 设别数据信息表
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设别数据信息表
     * 
     * @param ids 需要删除的设别数据信息表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设别数据信息表信息
     * 
     * @param id 设别数据信息表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void saveBatchData(IotMsgNotifyData iotMsgNotifyData) {
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        //判断是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId,deviceId).one();
        if(device==null){
            log.error("设备不存在，iotId："+deviceId );
            return;
        }
        //构建设备数据
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        List<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(s->{
            String eventTimeStr=s.getEventTime();
            LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            s.getProperties().forEach((k,v)->{
                DeviceData deviceData = DeviceData.builder()
                        .id(null)
                        .iotId(deviceId)
                        .functionId(k)
                        .dataValue(v.toString())
                        .alarmTime(eventTime)
                        .locationType(device.getLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .deviceName(device.getDeviceName())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .nickname(device.getNickname())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                .build();
                deviceDataList.add(deviceData);
            });
        });
        if(CollUtil.isNotEmpty(deviceDataList)){
            boolean result = saveBatch(deviceDataList);
            log.info("[批量保存上报的设备数据]结果：{}", result);
        }
        // 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
    }

    @Override
    public Page selectDeviceDataList(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = this.lambdaQuery()
                .eq(StringUtils.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
        return page;
    }
}
